package com.resource.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.jwt.JwtDecoders;
import org.springframework.security.web.SecurityFilterChain;

/**
 * @author chengyadong
 * @date 2023/12/5 16:52
 * @description 资源服务器配置文件
 */
@Configuration
@EnableWebSecurity
public class ResourceServiceConfig {
	//从配置文件中获取OAuth2 Jwt令牌签发者的uri
	@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
	String issuerUri;
	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		http.authorizeHttpRequests((authorizeHttpRequests) ->
				//当请求路径匹配到 /js/** , /css/** 这类静态资源的时候，不做认证，直接放行,其他请求进行拦截
				authorizeHttpRequests.requestMatchers("/js/**", "/css/**").permitAll()
						.anyRequest().authenticated()
		);
		http.oauth2ResourceServer(oauth2 -> oauth2
				//此处会远程调用授权服务器获取jwk
				.jwt(jwt -> jwt.decoder(JwtDecoders.fromIssuerLocation(issuerUri))));
		http.cors(Customizer.withDefaults());
		return http.build();
	}

}
